﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Domain;
using Data.Repositories;
using Data.ViewModels;

namespace CantinhodaCegonha.Controllers
{ 
    public class PerguntaController : Controller
    {
        private PerguntaRepository Perg_rep = new PerguntaRepository();
        private const int defaultEntryCount = 20;

        //
        // GET: /Pergunta/
        
        public ActionResult Index(int? entryCount)
        {
            if (!entryCount.HasValue)
                entryCount = defaultEntryCount;
            int totalItems;

            if (Request.IsAjaxRequest())
            {
                int page = entryCount.Value / defaultEntryCount;
                IEnumerable<PerguntaViewModel> PagedQuestions = Perg_rep.GetAllViewModel(page, defaultEntryCount, out totalItems);

                if (entryCount < totalItems)
                    AddMoreUrlToViewData(entryCount.Value);

                return  PartialView("_PerguntaList",PagedQuestions);
            }

            IEnumerable<PerguntaViewModel> questions = Perg_rep.GetAllViewModel(1, entryCount.Value, out totalItems);

            if (entryCount < totalItems)
                AddMoreUrlToViewData(entryCount.Value);

            return View(questions);
        }

        private void AddMoreUrlToViewData(int entryCount)
        {
            ViewData["moreUrl"] = Url.Action("Index", "Comunidade", new { entryCount = entryCount + defaultEntryCount });
            ViewData["entryCount"] = entryCount + defaultEntryCount;
        }

        //
        // GET: /Pergunta/Details/5

        public ViewResult Details(int id)
        {
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains(User.Identity.Name+ "Visita-" + id))
            {
                return View(Perg_rep.GetById(id, false));
            }
            else
            {
                HttpCookie cookie = new HttpCookie(User.Identity.Name + "Visita-" + id);
                cookie.Value = "Visitou";
                cookie.Expires = DateTime.MaxValue;
                HttpContext.Response.Cookies.Add(cookie);
                return View(Perg_rep.GetById(id, true));
            }
        }



        //public ViewResult Details(string nome)
        //{
        //    return View(Perg_rep.GetByNome(nome));
        //}


        [HttpPost]
        [Authorize]
        public JsonResult Vote(int id, int action)
        {
            if (Request.IsAjaxRequest())
            {

                if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains(User.Identity.Name + "Votou-" + id))
                {
                    return Json(new { id = id, votos = 0, success = "javotou" });
                }
                else
                {
                    HttpCookie cookie = new HttpCookie(User.Identity.Name + "Votou-" + id);
                    cookie.Value = "Votou";
                    cookie.Expires = DateTime.MaxValue;
                    HttpContext.Response.Cookies.Add(cookie);


                    PerguntaRepository resp = new PerguntaRepository();
                    int voto = resp.Votar(id, action, User.Identity.Name);
                    string sucesso = "true";
                    if (voto == -10000)
                        sucesso = "false";
                    if (voto == -10001)
                        sucesso = "votoproprio";

                    return Json(new { id = id, votos = voto, success = sucesso });
                }
            }
            return Json(new { id = id, votos = 0, success = "false" });
        }


        //
        // GET: /Pergunta/Create
        [Authorize]
        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Pergunta/Create

        [HttpPost]
        [Authorize]
        public ActionResult Create(Question question)
        {
            if(question== null){ ModelState.AddModelError("Erro","Ocorreu um erro!"); return View();}

            if (!Microsoft.Web.Helpers.ReCaptcha.Validate("6LdCisYSAAAAAJy_5kDLK3x03ZfVGfi2TPppD-n_"))
            { return View(); }
            
            if (ModelState.IsValid)
            {
                Perg_rep.Create(question, User.Identity.Name,Request["Tags"],Request["avisar"]);
                return RedirectToAction("Index", "Comunidade"); 
            }

            return View(question);
        }
        
        //
        // GET: /Pergunta/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View(Perg_rep.GetById(id,false));
        }

        public ActionResult Edit(string nome)
        {
            return View(Perg_rep.GetByNome(nome,false));
        }

        //
        // POST: /Pergunta/Edit/5

        [HttpPost]
        public ActionResult Edit(Question question)
        {
            if (ModelState.IsValid)
            {
                Perg_rep.Update(question);
                return RedirectToAction("Index");
            }
            return View(question);
        }

        //
        // GET: /Pergunta/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View(Perg_rep.GetById(id,false));
        }

        //
        // POST: /Pergunta/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Perg_rep.Delete(id);
            return RedirectToAction("Index");
        }


        public ActionResult Tagged(string id)
        {
            return View(Perg_rep.GetAllByTag(id));
        }
    }
}